home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 2 / AACD 2.iso / AACD / Programming / perlman / man / perlref.txt < prev    next >
Encoding:
Text File  |  1999-09-09  |  19.8 KB  |  491 lines

  1. NAME
  2.        perlref - Perl references and nested data structures
  3.  
  4. DESCRIPTION
  5.        Before release 5 of Perl it was difficult to represent
  6.        complex data structures, because all references had to be
  7.        symbolic, and even that was difficult to do when you
  8.        wanted to refer to a variable rather than a symbol table
  9.        entry.  Perl 5 not only makes it easier to use symbolic
  10.        references to variables, but lets you have "hard"
  11.        references to any piece of data.  Any scalar may hold a
  12.        hard reference.  Since arrays and hashes contain scalars,
  13.        you can now easily build arrays of arrays, arrays of
  14.        hashes, hashes of arrays, arrays of hashes of functions,
  15.        and so on.
  16.  
  17.        Hard references are smart--they keep track of reference
  18.        counts for you, automatically freeing the thing referred
  19.        to when its reference count goes to zero.  If that thing
  20.        happens to be an object, the object is destructed.  See
  21.        the perlobj manpage for more about objects.  (In a sense,
  22.        everything in Perl is an object, but we usually reserve
  23.        the word for references to objects that have been
  24.        officially "blessed" into a class package.)
  25.  
  26.        A symbolic reference contains the name of a variable, just
  27.        as a symbolic link in the filesystem merely contains the
  28.        name of a file.  The *glob notation is a kind of symbolic
  29.        reference.  Hard references are more like hard links in
  30.        the file system: merely another way at getting at the same
  31.        underlying object, irrespective of its name.
  32.  
  33.        "Hard" references are easy to use in Perl.  There is just
  34.        one overriding principle:  Perl does no implicit
  35.        referencing or dereferencing.  When a scalar is holding a
  36.        reference, it always behaves as a scalar.  It doesn't
  37.        magically start being an array or a hash unless you tell
  38.        it so explicitly by dereferencing it.
  39.  
  40.        References can be constructed several ways.
  41.  
  42.        1.  By using the backslash operator on a variable,
  43.            subroutine, or value.  (This works much like the &
  44.            (address-of) operator works in C.)  Note that this
  45.            typically creates ANOTHER reference to a variable,
  46.            since there's already a reference to the variable in
  47.            the symbol table.  But the symbol table reference
  48.            might go away, and you'll still have the reference
  49.            that the backslash returned.  Here are some examples:
  50.  
  51.  
  52.  
  53.                $scalarref = \$foo;
  54.                $arrayref  = \@ARGV;
  55.                $hashref   = \%ENV;
  56.                $coderef   = \&handler;
  57.                $globref   = \*STDOUT;
  58.  
  59.        2.  A reference to an anonymous array can be constructed
  60.            using square brackets:
  61.  
  62.                $arrayref = [1, 2, ['a', 'b', 'c']];
  63.  
  64.            Here we've constructed a reference to an anonymous
  65.            array of three elements whose final element is itself
  66.            reference to another anonymous array of three
  67.            elements.  (The multidimensional syntax described
  68.            later can be used to access this.  For example, after
  69.            the above, $arrayref->[2][1] would have the value
  70.            "b".)
  71.  
  72.            Note that taking a reference to an enumerated list is
  73.            not the same as using square brackets--instead it's
  74.            the same as creating a list of references!
  75.  
  76.                @list = (\$a, \$b, \$c);
  77.                @list = \($a, $b, $c);      # same thing!
  78.  
  79.        3.  A reference to an anonymous hash can be constructed
  80.            using curly brackets:
  81.  
  82.                $hashref = {
  83.                    'Adam'  => 'Eve',
  84.                    'Clyde' => 'Bonnie',
  85.                };
  86.  
  87.            Anonymous hash and array constructors can be
  88.            intermixed freely to produce as complicated a
  89.            structure as you want.  The multidimensional syntax
  90.            described below works for these too.  The values above
  91.            are literals, but variables and expressions would work
  92.            just as well, because assignment operators in Perl
  93.            (even within local() or my()) are executable
  94.            statements, not compile-time declarations.
  95.  
  96.            Because curly brackets (braces) are used for several
  97.            other things including BLOCKs, you may occasionally
  98.            have to disambiguate braces at the beginning of a
  99.            statement by putting a + or a return in front so that
  100.            Perl realizes the opening brace isn't starting a
  101.            BLOCK.  The economy and mnemonic value of using
  102.            curlies is deemed worth this occasional extra hassle.
  103.  
  104.            For example, if you wanted a function to make a new
  105.            hash and return a reference to it, you have these
  106.            options:
  107.  
  108.                sub hashem {        { @_ } }   # silently wrong
  109.                sub hashem {       +{ @_ } }   # ok
  110.                sub hashem { return { @_ } }   # ok
  111.  
  112.        4.  A reference to an anonymous subroutine can be
  113.            constructed by using sub without a subname:
  114.  
  115.                $coderef = sub { print "Boink!\n" };
  116.  
  117.            Note the presence of the semicolon.  Except for the
  118.            fact that the code inside isn't executed immediately,
  119.            a sub {} is not so much a declaration as it is an
  120.            operator, like do{} or eval{}.  (However, no matter
  121.            how many times you execute that line (unless you're in
  122.            an eval("...")), $coderef will still have a reference
  123.            to the SAME anonymous subroutine.)
  124.  
  125.            Anonymous subroutines act as closures with respect to
  126.            my() variables, that is, variables visible lexically
  127.            within the current scope.  Closure is a notion out of
  128.            the Lisp world that says if you define an anonymous
  129.            function in a particular lexical context, it pretends
  130.            to run in that context even when it's called outside
  131.            of the context.
  132.  
  133.            In human terms, it's a funny way of passing arguments
  134.            to a subroutine when you define it as well as when you
  135.            call it.  It's useful for setting up little bits of
  136.            code to run later, such as callbacks.  You can even do
  137.            object-oriented stuff with it, though Perl provides a
  138.            different mechanism to do that already--see the
  139.            perlobj manpage.
  140.  
  141.            You can also think of closure as a way to write a
  142.            subroutine template without using eval.  (In fact, in
  143.            version 5.000, eval was the only way to get closures.
  144.            You may wish to use "require 5.001" if you use
  145.            closures.)
  146.  
  147.            Here's a small example of how closures works:
  148.  
  149.                sub newprint {
  150.                    my $x = shift;
  151.                    return sub { my $y = shift; print "$x, $y!\n"; };
  152.                }
  153.                $h = newprint("Howdy");
  154.                $g = newprint("Greetings");
  155.  
  156.                # Time passes...
  157.  
  158.                &$h("world");
  159.                &$g("earthlings");
  160.  
  161.            This prints
  162.  
  163.                Howdy, world!
  164.                Greetings, earthlings!
  165.  
  166.            Note particularly that $x continues to refer to the
  167.            value passed into newprint() despite the fact that the
  168.            "my $x" has seemingly gone out of scope by the time
  169.            the anonymous subroutine runs.  That's what closure is
  170.            all about.
  171.  
  172.            This only applies to lexical variables, by the way.
  173.            Dynamic variables continue to work as they have always
  174.            worked.  Closure is not something that most Perl
  175.            programmers need trouble themselves about to begin
  176.            with.
  177.  
  178.        5.  References are often returned by special subroutines
  179.            called constructors.  Perl objects are just references
  180.            to a special kind of object that happens to know which
  181.            package it's associated with.  Constructors are just
  182.            special subroutines that know how to create that
  183.            association.  They do so by starting with an ordinary
  184.            reference, and it remains an ordinary reference even
  185.            while it's also being an object.  Constructors are
  186.            customarily named new(), but don't have to be:
  187.  
  188.                $objref = new Doggie (Tail => 'short', Ears => 'long');
  189.  
  190.        6.  References of the appropriate type can spring into
  191.            existence if you dereference them in a context that
  192.            assumes they exist.  Since we haven't talked about
  193.            dereferencing yet, we can't show you any examples yet.
  194.  
  195.        7.  References to filehandles can be created by taking a
  196.            reference to a typeglob.  This is currently the best
  197.            way to pass filehandles into or out of subroutines, or
  198.            to store them in larger data structures.
  199.  
  200.                splutter(\*STDOUT);
  201.                sub splutter {
  202.                    my $fh = shift;
  203.                    print $fh "her um well a hmmm\n";
  204.                }
  205.  
  206.                $rec = get_rec(\*STDIN);
  207.                sub get_rec {
  208.                    my $fh = shift;
  209.                    return scalar <$fh>;
  210.                }
  211.        That's it for creating references.  By now you're probably
  212.        dying to know how to use references to get back to your
  213.        long-lost data.  There are several basic methods.
  214.  
  215.        1.  Anywhere you'd put an identifier as part of a variable
  216.            or subroutine name, you can replace the identifier
  217.            with a simple scalar variable containing a reference
  218.            of the correct type:
  219.  
  220.                $bar = $$scalarref;
  221.                push(@$arrayref, $filename);
  222.                $$arrayref[0] = "January";
  223.                $$hashref{"KEY"} = "VALUE";
  224.                &$coderef(1,2,3);
  225.                print $globref "output\n";
  226.  
  227.            It's important to understand that we are specifically
  228.            NOT dereferencing $arrayref[0] or $hashref{"KEY"}
  229.            there.  The dereference of the scalar variable happens
  230.            BEFORE it does any key lookups.  Anything more
  231.            complicated than a simple scalar variable must use
  232.            methods 2 or 3 below.  However, a "simple scalar"
  233.            includes an identifier that itself uses method 1
  234.            recursively.  Therefore, the following prints "howdy".
  235.  
  236.                $refrefref = \\\"howdy";
  237.                print $$$$refrefref;
  238.  
  239.        2.  Anywhere you'd put an identifier as part of a variable
  240.            or subroutine name, you can replace the identifier
  241.            with a BLOCK returning a reference of the correct
  242.            type.  In other words, the previous examples could be
  243.            written like this:
  244.  
  245.                $bar = ${$scalarref};
  246.                push(@{$arrayref}, $filename);
  247.                ${$arrayref}[0] = "January";
  248.                ${$hashref}{"KEY"} = "VALUE";
  249.                &{$coderef}(1,2,3);
  250.                $globref->print("output\n");  # iff you use FileHandle
  251.  
  252.            Admittedly, it's a little silly to use the curlies in
  253.            this case, but the BLOCK can contain any arbitrary
  254.            expression, in particular, subscripted expressions:
  255.  
  256.                &{ $dispatch{$index} }(1,2,3);      # call correct routine
  257.  
  258.            Because of being able to omit the curlies for the
  259.            simple case of $$x, people often make the mistake of
  260.            viewing the dereferencing symbols as proper operators,
  261.            and wonder about their precedence.  If they were,
  262.            though, you could use parens instead of braces.
  263.            That's not the case.  Consider the difference below;
  264.            case 0 is a short-hand version of case 1, NOT case 2:
  265.  
  266.                $$hashref{"KEY"}   = "VALUE";       # CASE 0
  267.                ${$hashref}{"KEY"} = "VALUE";       # CASE 1
  268.                ${$hashref{"KEY"}} = "VALUE";       # CASE 2
  269.                ${$hashref->{"KEY"}} = "VALUE";     # CASE 3
  270.  
  271.            Case 2 is also deceptive in that you're accessing a
  272.            variable called %hashref, not dereferencing through
  273.            $hashref to the hash it's presumably referencing.
  274.            That would be case 3.
  275.  
  276.        3.  The case of individual array elements arises often
  277.            enough that it gets cumbersome to use method 2.  As a
  278.            form of syntactic sugar, the two lines like that above
  279.            can be written:
  280.  
  281.                $arrayref->[0] = "January";
  282.                $hashref->{"KEY"} = "VALUE";
  283.  
  284.            The left side of the array can be any expression
  285.            returning a reference, including a previous
  286.            dereference.  Note that $array[$x] is NOT the same
  287.            thing as $array->[$x] here:
  288.  
  289.                $array[$x]->{"foo"}->[0] = "January";
  290.  
  291.            This is one of the cases we mentioned earlier in which
  292.            references could spring into existence when in an
  293.            lvalue context.  Before this statement, $array[$x] may
  294.            have been undefined.  If so, it's automatically
  295.            defined with a hash reference so that we can look up
  296.            {"foo"} in it.  Likewise $array[$x]->{"foo"} will
  297.            automatically get defined with an array reference so
  298.            that we can look up [0] in it.
  299.  
  300.            One more thing here.  The arrow is optional BETWEEN
  301.            brackets subscripts, so you can shrink the above down
  302.            to
  303.  
  304.                $array[$x]{"foo"}[0] = "January";
  305.  
  306.            Which, in the degenerate case of using only ordinary
  307.            arrays, gives you multidimensional arrays just like
  308.            C's:
  309.  
  310.                $score[$x][$y][$z] += 42;
  311.  
  312.            Well, okay, not entirely like C's arrays, actually.  C
  313.            doesn't know how to grow its arrays on demand.  Perl
  314.            does.
  315.  
  316.        4.  If a reference happens to be a reference to an object,
  317.            then there are probably methods to access the things
  318.            referred to, and you should probably stick to those
  319.            methods unless you're in the class package that
  320.            defines the object's methods.  In other words, be
  321.            nice, and don't violate the object's encapsulation
  322.            without a very good reason.  Perl does not enforce
  323.            encapsulation.  We are not totalitarians here.  We do
  324.            expect some basic civility though.
  325.  
  326.        The ref() operator may be used to determine what type of
  327.        thing the reference is pointing to.  See the perlfunc
  328.        manpage.
  329.  
  330.        The bless() operator may be used to associate a reference
  331.        with a package functioning as an object class.  See the
  332.        perlobj manpage.
  333.  
  334.        A typeglob may be dereferenced the same way a reference
  335.        can, since the dereference syntax always indicates the
  336.        kind of reference desired.  So ${*foo} and ${\$foo} both
  337.        indicate the same scalar variable.
  338.  
  339.        Here's a trick for interpolating a subroutine call into a
  340.        string:
  341.  
  342.            print "My sub returned @{[mysub(1,2,3)]} that time.\n";
  343.  
  344.        The way it works is that when the @{...} is seen in the
  345.        double-quoted string, it's evaluated as a block.  The
  346.        block creates a reference to an anonymous array containing
  347.        the results of the call to mysub(1,2,3).  So the whole
  348.        block returns a reference to an array, which is then
  349.        dereferenced by @{...} and stuck into the double-quoted
  350.        string. This chicanery is also useful for arbitrary
  351.        expressions:
  352.  
  353.            print "That yeilds @{[$n + 5]} widgets\n";
  354.  
  355.        Symbolic references
  356.  
  357.        We said that references spring into existence as necessary
  358.        if they are undefined, but we didn't say what happens if a
  359.        value used as a reference is already defined, but ISN'T a
  360.        hard reference.  If you use it as a reference in this
  361.        case, it'll be treated as a symbolic reference.  That is,
  362.        the value of the scalar is taken to be the NAME of a
  363.        variable, rather than a direct link to a (possibly)
  364.        anonymous value.
  365.  
  366.        People frequently expect it to work like this.  So it
  367.        does.
  368.  
  369.  
  370.            $name = "foo";
  371.            $$name = 1;                 # Sets $foo
  372.            ${$name} = 2;               # Sets $foo
  373.            ${$name x 2} = 3;           # Sets $foofoo
  374.            $name->[0] = 4;             # Sets $foo[0]
  375.            @$name = ();                # Clears @foo
  376.            &$name();                   # Calls &foo() (as in Perl 4)
  377.            $pack = "THAT";
  378.            ${"${pack}::$name"} = 5;    # Sets $THAT::foo without eval
  379.  
  380.        This is very powerful, and slightly dangerous, in that
  381.        it's possible to intend (with the utmost sincerity) to use
  382.        a hard reference, and accidentally use a symbolic
  383.        reference instead.  To protect against that, you can say
  384.  
  385.            use strict 'refs';
  386.  
  387.        and then only hard references will be allowed for the rest
  388.        of the enclosing block.  An inner block may countermand
  389.        that with
  390.  
  391.            no strict 'refs';
  392.  
  393.        Only package variables are visible to symbolic references.
  394.        Lexical variables (declared with my()) aren't in a symbol
  395.        table, and thus are invisible to this mechanism.  For
  396.        example:
  397.  
  398.            local($value) = 10;
  399.            $ref = \$value;
  400.            {
  401.                my $value = 20;
  402.                print $$ref;
  403.            }
  404.  
  405.        This will still print 10, not 20.  Remember that local()
  406.        affects package variables, which are all "global" to the
  407.        package.
  408.  
  409.        Not-so-symbolic references
  410.  
  411.        A new feature contributing to readability in 5.001 is that
  412.        the brackets around a symbolic reference behave more like
  413.        quotes, just as they always have within a string.  That
  414.        is,
  415.  
  416.            $push = "pop on ";
  417.            print "${push}over";
  418.  
  419.        has always meant to print "pop on over", despite the fact
  420.        that push is a reserved word.  This has been generalized
  421.        to work the same outside of quotes, so that
  422.  
  423.            print ${push} . "over";
  424.        and even
  425.  
  426.            print ${ push } . "over";
  427.  
  428.        will have the same effect.  (This would have been a syntax
  429.        error in 5.000, though Perl 4 allowed it in the spaceless
  430.        form.)  Note that this construct is not considered to be a
  431.        symbolic reference when you're using strict refs:
  432.  
  433.            use strict 'refs';
  434.            ${ bareword };      # Okay, means $bareword.
  435.            ${ "bareword" };    # Error, symbolic reference.
  436.  
  437.        Similarly, because of all the subscripting that is done
  438.        using single words, we've applied the same rule to any
  439.        bareword that is used for subscripting a hash.  So now,
  440.        instead of writing
  441.  
  442.            $array{ "aaa" }{ "bbb" }{ "ccc" }
  443.  
  444.        you can just write
  445.  
  446.            $array{ aaa }{ bbb }{ ccc }
  447.  
  448.        and not worry about whether the subscripts are reserved
  449.        words.  In the rare event that you do wish to do something
  450.        like
  451.  
  452.            $array{ shift }
  453.  
  454.        you can force interpretation as a reserved word by adding
  455.        anything that makes it more than a bareword:
  456.  
  457.            $array{ shift() }
  458.            $array{ +shift }
  459.            $array{ shift @_ }
  460.  
  461.        The -w switch will warn you if it interprets a reserved
  462.        word as a string.  But it will no longer warn you about
  463.        using lowercase words, since the string is effectively
  464.        quoted.
  465.  
  466. WARNING
  467.        You may not (usefully) use a reference as the key to a
  468.        hash.  It will be converted into a string:
  469.  
  470.            $x{ \$a } = $a;
  471.  
  472.        If you try to dereference the key, it won't do a hard
  473.        dereference, and you won't accomplish what you're
  474.        attemping.  You might want to do something more like
  475.  
  476.            $r = \@a;
  477.            $x{ $r } = $r;
  478.        And then at least you can use the values(), which will be
  479.        real refs, instead of the keys(), which won't.
  480.  
  481. SEE ALSO
  482.        Besides the obvious documents, source code can be
  483.        instructive.  Some rather pathological examples of the use
  484.        of references can be found in the t/op/ref.t regression
  485.        test in the Perl source directory.
  486.  
  487.        See also the perldsc manpage and the perllol manpage for
  488.        how to use references to create complex data structures,
  489.        and the perlobj manpage for how to use them to create
  490.        objects.
  491.